"""智能意图分类节点"""

import re
from typing import Dict, List, Tuple
from core.graph.chat_graph import ChatState, IntentType


class IntentClassifier:
    """智能意图分类器"""
    
    def __init__(self):
        self.intent_patterns = {
            IntentType.ERROR_DIAGNOSIS: [
                r"(error|错误|报错|panic|exception|failed|failure|bug|问题)",
                r"(不工作|不运行|编译失败|运行失败|崩溃)",
                r"(traceback|stack trace|调试|debug)",
                r"(修复|fix|解决|solve)"
            ],
            IntentType.CODE_ANALYSIS: [
                r"(分析|解释|explain|analyze|理解|understand)",
                r"(这段代码|这个函数|这个合约|code review)",
                r"(优化|optimize|改进|improve|重构|refactor)",
                r"(性能|performance|效率|efficiency)"
            ],
            IntentType.CODE_GENERATION: [
                r"(生成|generate|创建|create|写|write|实现|implement)",
                r"(示例|example|demo|模板|template)",
                r"(帮我写|help me write|给我一个|give me a)"
            ],
            IntentType.DEEP_RESEARCH: [
                r"(深入|详细|深度|详尽|全面|comprehensive|detailed|in-depth)",
                r"(研究|research|分析|analysis|探讨|discuss)",
                r"(原理|principle|机制|mechanism|底层|underlying)",
                r"(比较|compare|对比|contrast|区别|difference)"
            ],
            IntentType.TUTORIAL: [
                r"(教程|tutorial|指南|guide|学习|learn|入门|getting started)",
                r"(如何|how to|怎么|怎样|步骤|step)",
                r"(从零开始|from scratch|基础|basic|初学者|beginner)"
            ],
            IntentType.QA: [
                r"(什么是|what is|是什么|定义|definition)",
                r"(为什么|why|原因|reason|目的|purpose)",
                r"(特点|特性|feature|特征|characteristic|有什么.*特点)",
                r"(语法|syntax|用法|usage|规则|rule)",
                r"(介绍|简介|概述|overview|说明|explain)",
                r"(类型|type|种类|category|分类)"
            ]
        }
        
        self.code_indicators = [
            "fn ", "struct ", "trait ", "impl ", "mod ", "contract ",
            "enum ", "let ", "mut ", "const ", "use ", "pub ",
            "```", "cairo", "starknet"
        ]
        
        self.error_indicators = [
            "error:", "panic:", "failed to", "cannot", "undefined",
            "compilation error", "runtime error", "type error"
        ]

    def extract_features(self, text: str) -> Dict[str, float]:
        """提取文本特征"""
        features = {}
        text_lower = text.lower()
        
        # 基础特征
        features["has_code_block"] = 1.0 if "```" in text else 0.0
        features["has_cairo_keywords"] = sum(1 for kw in self.code_indicators if kw in text_lower) / len(self.code_indicators)
        features["has_error_indicators"] = sum(1 for ei in self.error_indicators if ei in text_lower) / len(self.error_indicators)
        features["question_marks"] = text.count("?") / max(len(text), 1)
        features["text_length"] = min(len(text) / 1000, 1.0)  # 归一化长度
        
        # 意图模式匹配
        for intent, patterns in self.intent_patterns.items():
            pattern_matches = sum(1 for pattern in patterns if re.search(pattern, text_lower, re.IGNORECASE))
            features[f"pattern_{intent.value}"] = pattern_matches / len(patterns)
        
        return features

    def calculate_intent_scores(self, features: Dict[str, float]) -> Dict[IntentType, float]:
        """计算各意图的得分"""
        scores = {}
        
        # 错误诊断得分
        scores[IntentType.ERROR_DIAGNOSIS] = (
            features["has_error_indicators"] * 0.4 +
            features["pattern_error_diagnosis"] * 0.4 +
            features["has_code_block"] * 0.2
        )
        
        # 代码分析得分
        scores[IntentType.CODE_ANALYSIS] = (
            features["has_code_block"] * 0.3 +
            features["has_cairo_keywords"] * 0.3 +
            features["pattern_code_analysis"] * 0.4
        )
        
        # 代码生成得分
        scores[IntentType.CODE_GENERATION] = (
            features["pattern_code_generation"] * 0.5 +
            features["has_cairo_keywords"] * 0.3 +
            (1 - features["has_code_block"]) * 0.2  # 通常没有现有代码
        )
        
        # 深度研究得分
        scores[IntentType.DEEP_RESEARCH] = (
            features["pattern_deep_research"] * 0.6 +
            features["text_length"] * 0.2 +
            features["question_marks"] * 0.2
        )
        
        # 教程得分
        scores[IntentType.TUTORIAL] = (
            features["pattern_tutorial"] * 0.7 +
            features["question_marks"] * 0.3
        )
        
        # 知识问答得分
        scores[IntentType.QA] = (
            features["pattern_qa"] * 0.6 +
            features["question_marks"] * 0.4
        )
        
        # 其他类型（默认得分）
        scores[IntentType.OTHER] = 0.1
        
        return scores

    def classify(self, text: str) -> Tuple[IntentType, float]:
        """分类意图并返回置信度"""
        features = self.extract_features(text)
        scores = self.calculate_intent_scores(features)
        
        # 找到最高得分的意图
        best_intent = max(scores.keys(), key=lambda k: scores[k])
        confidence = scores[best_intent]
        
        # 如果置信度太低，归类为其他
        if confidence < 0.3:
            return IntentType.OTHER, confidence
        
        return best_intent, confidence


# 全局分类器实例
intent_classifier = IntentClassifier()


def classify_intent(state: ChatState) -> ChatState:
    """智能意图分类节点"""
    user_text = state["messages"][-1]["content"] if state["messages"] else ""
    
    # 使用智能分类器
    intent, confidence = intent_classifier.classify(user_text)
    
    # 更新状态
    state["user_intent"] = intent
    state["confidence_score"] = confidence
    
    # 根据意图设置下一步动作
    if intent == IntentType.ERROR_DIAGNOSIS:
        state["next_action"] = "error_analysis"
    elif intent == IntentType.CODE_ANALYSIS:
        state["next_action"] = "code_parsing"
    elif intent == IntentType.DEEP_RESEARCH:
        state["next_action"] = "research_planning"
        state["research_depth"] = 3  # 深度研究模式
    elif intent == IntentType.CODE_GENERATION:
        state["next_action"] = "knowledge_retrieval"
    else:
        state["next_action"] = "knowledge_retrieval"
    
    return state
